import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JOptionPane;

public class MathTrainer
{
    private static final Random randomNumbers = new Random();
    private int counter = 0;
    private int successes = 0;
    private List<String> fails = new ArrayList<>();
    
    public void Run()
    {
        exercisesLoop();
        Summarize();
    }
    
    private void exercisesLoop()
    {
        String dialogResult;
        do
        {
            counter++;
            int tries = 0;
            Operation current = getRandomExcercise();

            do
            {
                dialogResult = JOptionPane.showInputDialog(null, current.toString(), "Exercise #" + counter + " Try #" + ++tries, JOptionPane.QUESTION_MESSAGE);
            } while(!isBlank(dialogResult) && !dialogResult.trim().equals(current.getResult()) && tries < 3);
            
            if(isBlank(dialogResult))
                return;
            
            if(3 == tries)
            {
                JOptionPane.showMessageDialog(null, "Sorry, the correct answer is " + current.getResult());
                fails.add(current.toString());
                tries = 0;
            }
            else
                successes++;
        } while(!isBlank(dialogResult));
    }
        
    private Operation getRandomExcercise()
    {
        switch(randomNumbers.nextInt(3))
        {
            case 0:
                return new Addition();
            case 1:
                return new Subtraction();
            case 2:
                return new Multiplication();
            default:
                return new Division();
        }
    }
    
    private boolean isBlank(String str) 
    {
        return str == null || str.trim().length() == 0;
    }

    private void Summarize()
    {
        counter--; //the last exercise should be ignored, as the user terminated the program without answering
        StringBuilder message = new StringBuilder();
        long score = counter == 0 ? 0 : Math.round((double)successes / counter * 100);
        message.append("Your score is: " + score + "%\n");
        if(successes < counter)
        {
            message.append("Here are the exercises you did not answer correcttly:");
            for(String s : fails)
                message.append("\n" + s);
        }
        JOptionPane.showMessageDialog(null, message);
    }
    
}
